const { app, BrowserWindow, ipcMain, dialog, globalShortcut, protocol } = require('electron');
const path = require('path');
const fs = require('fs');
// 添加 zlib 模块用于文件压缩
const zlib = require('zlib');

// 禁用硬件加速以提高Windows 7兼容性
if (process.platform === 'win32') {
  app.disableHardwareAcceleration();
}

// 添加 Windows 7 兼容性处理
app.commandLine.appendSwitch('disable-gpu');
app.commandLine.appendSwitch('disable-gpu-compositing');
app.commandLine.appendSwitch('disable-web-security');

function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      disableBlinkFeatures: 'Auxclick', // 禁用不必要的blink功能
      sandbox: true // 如果可能，启用沙箱
    }
  });

  // 禁用危险快捷键
  mainWindow.webContents.on('before-input-event', (event, input) => {
    const { control, shift, alt, meta, key } = input;
    // 禁用开发者工具快捷键 (Ctrl/Cmd + Shift + I)
    if ((control || meta) && shift && key.toLowerCase() === 'i') {
      event.preventDefault();
    }
    // 禁用刷新快捷键 (Ctrl/Cmd + R)
    if ((control || meta) && key.toLowerCase() === 'r') {
      event.preventDefault();
    }
    // 禁用强制刷新快捷键 (Ctrl/Cmd + Shift + R)
    if ((control || meta) && shift && key.toLowerCase() === 'r') {
      event.preventDefault();
    }
  });

  mainWindow.loadFile('index.html');
  // 隐藏菜单栏
  mainWindow.setMenuBarVisibility(false);
  // 开发时打开开发者工具
  //mainWindow.webContents.openDevTools();
}

app.whenReady().then(() => {
  // 添加对 build 目录静态资源的访问支持
  protocol.registerFileProtocol('build', (request, callback) => {
    const url = request.url.substr(8);
    callback({ path: path.join(__dirname, 'build', url) });
  });
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});


// 退出程序时确保所有窗口都被关闭
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

// 公共压缩函数
async function compressBuffer(fileBuffer, fileName) {
  // 使用 JSZip 压缩文件
  const JSZip = require('jszip');
  
  const zip = new JSZip();
  zip.file(fileName, fileBuffer);
  
  const compressedBuffer = await zip.generateAsync({
    type: 'nodebuffer',
    compression: 'DEFLATE',
    compressionOptions: {
      level: 6
    },
    encodeFileName: function (string) {
      // 使用UTF-8编码文件名
      return Buffer.from(string, 'utf-8');
    }
  });
  
  return compressedBuffer;
}

// IPC 处理程序
ipcMain.handle('show-open-dialog', async () => {
  console.log('显示文件选择对话框');
  const result = await dialog.showOpenDialog({
    properties: ['openFile']
  });
  console.log('文件选择结果:', result);
  return result;
});

ipcMain.handle('get-file-info', async (event, filePath) => {
  try {
    const stats = fs.statSync(filePath);
    return {
      name: path.basename(filePath),
      size: stats.size,
      path: filePath
    };
  } catch (error) {
    console.error('获取文件信息出错:', error);
    return { error: error.message };
  }
});

// 添加文件压缩 IPC 处理程序
ipcMain.handle('compress-file', async (event, filePath) => {
  console.log('开始压缩文件:', filePath);
  try {
    const fileBuffer = fs.readFileSync(filePath);
    console.log('文件读取成功，大小:', fileBuffer.length);
    
    const fileName = path.basename(filePath);
    const compressedBuffer = await compressBuffer(fileBuffer, fileName);
    
    console.log('文件压缩成功，压缩后大小:', compressedBuffer.length);
    
    // 创建压缩文件路径 - 使用临时目录
    const compressedFilePath = path.join(app.getPath('temp'), fileName + '.zip');
    fs.writeFileSync(compressedFilePath, compressedBuffer);
    console.log('压缩文件保存至:', compressedFilePath);
    
    const result = {
      success: true,
      path: compressedFilePath,
      originalSize: fileBuffer.length,
      compressedSize: compressedBuffer.length
    };
    console.log('压缩结果:', result);
    return result;
  } catch (error) {
    console.error('文件压缩出错:', error);
    return { success: false, error: error.message };
  }
});


// 保存并压缩文件
ipcMain.handle('save-and-compress-file', async (event, fileName, fileData) => {
  console.log('保存并压缩文件:', fileName);
  try {
    // 创建临时文件
    const tempPath = path.join(app.getPath('temp'), fileName);
    fs.writeFileSync(tempPath, Buffer.from(fileData));
    
    // 直接复用压缩逻辑而不是调用函数名
    console.log('开始压缩文件:', tempPath);
    const fileBuffer = fs.readFileSync(tempPath);
    console.log('文件读取成功，大小:', fileBuffer.length);
    
    const compressedBuffer = await compressBuffer(fileBuffer, fileName);
    
    console.log('文件压缩成功，压缩后大小:', compressedBuffer.length);
    
    // 创建压缩文件路径 - 使用临时目录
    const compressedFilePath = path.join(app.getPath('temp'), fileName + '.zip');
    fs.writeFileSync(compressedFilePath, compressedBuffer);
    console.log('压缩文件保存至:', compressedFilePath);
    
    const result = {
      success: true,
      path: compressedFilePath,
      originalSize: fileBuffer.length,
      compressedSize: compressedBuffer.length
    };
    console.log('压缩结果:', result);
    return result;
  } catch (error) {
    console.error('保存并压缩文件出错:', error);
    return { success: false, error: error.message };
  }
});

// 检查文件大小
ipcMain.handle('check-file-size', async (event, filePath) => {
  try {
    const stats = fs.statSync(filePath);
    const maxSize = 10 * 1024 * 1024; // 10MB
    return {
      size: stats.size,
      exceedsLimit: stats.size > maxSize,
      maxSize: maxSize
    };
  } catch (error) {
    return { error: error.message };
  }
});

// 添加删除文件的IPC处理程序
ipcMain.handle('delete-file', async (event, filePath) => {
  try {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
      console.log('文件已删除:', filePath);
      return { success: true };
    } else {
      console.log('文件不存在:', filePath);
      return { success: false, error: '文件不存在' };
    }
  } catch (error) {
    console.error('删除文件时出错:', error);
    return { success: false, error: error.message };
  }
});